<template>
  <n-grid cols="1" responsive="screen">
    <n-grid-item>
      <n-card title="基本设置" class="mb-4">
        <n-form :label-width="80" :model="formValue" :rules="rules" ref="formRef">
          <n-form-item label="55环境地址" path="env55">
            <n-input
              v-model:value="formValue.env55"
              placeholder="请输入55环境的服务器地址"
              clearable
            />
          </n-form-item>

          <n-form-item label="54环境地址" path="env54">
            <n-input
              v-model:value="formValue.env54"
              placeholder="请输入54环境的服务器地址"
              clearable
            />
          </n-form-item>

          <n-form-item label="本地环境地址" path="localhost">
            <n-input
              v-model:value="formValue.localhost"
              placeholder="请输入本地环境的服务器地址"
              clearable
            />
          </n-form-item>

          <n-form-item label="Token Key" path="key">
            <n-input
              v-model:value="formValue.key"
              placeholder="请输入Token Key"
              clearable
              show-password-on="click"
            />
          </n-form-item>
        </n-form>
      </n-card>

      <div>
        <n-space>
          <n-button type="primary" @click="formSubmit" :loading="loading"> 保存设置</n-button>
          <n-button @click="loadSettings"> 重置</n-button>
        </n-space>
      </div>
    </n-grid-item>
  </n-grid>
</template>

<script lang="ts" setup>
  import { reactive, ref, onMounted } from 'vue';
  import { useMessage } from 'naive-ui';
  import { invoke } from '@tauri-apps/api/core';

  interface AutoLoginSettings {
    env55: string;
    env54: string;
    localhost: string;
    key: string; // 新增key字段
  }

  const rules = {
    env55: {
      validator: (rule: any, value: string) => {
        if (value && !isValidUrl(value)) {
          return new Error('请输入有效的URL地址');
        }
        return true;
      },
      trigger: 'blur',
    },
    env54: {
      validator: (rule: any, value: string) => {
        if (value && !isValidUrl(value)) {
          return new Error('请输入有效的URL地址');
        }
        return true;
      },
      trigger: 'blur',
    },
    localhost: {
      validator: (rule: any, value: string) => {
        if (value && !isValidUrl(value)) {
          return new Error('请输入有效的URL地址');
        }
        return true;
      },
      trigger: 'blur',
    },
  };

  // URL验证函数
  const isValidUrl = (url: string): boolean => {
    try {
      new URL(url);
      return true;
    } catch {
      // 也允许简单的IP:端口格式
      const ipPortRegex = /^(https?:\/\/)?(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(:\d+)?(\/.*)?$/;
      const localhostRegex = /^(https?:\/\/)?(localhost)(:\d+)?(\/.*)?$/;
      return ipPortRegex.test(url) || localhostRegex.test(url);
    }
  };

  const formRef: any = ref(null);
  const message = useMessage();
  const loading = ref(false);

  const formValue = reactive<AutoLoginSettings>({
    env55: 'http://192.168.1.55:8080',
    env54: 'http://192.168.1.54:8080',
    localhost: 'http://localhost:8080',
    key: '', // 新增key字段默认值
  });

  // 加载自动登录设置
  async function loadSettings() {
    try {
      const settings = await invoke<any>('get_user_settings');
      Object.assign(formValue, {
        env55: settings.auto_login?.environments?.env_55 || 'http://192.168.1.55:8080',
        env54: settings.auto_login?.environments?.env_54 || 'http://192.168.1.54:8080',
        localhost: settings.auto_login?.environments?.localhost || 'http://localhost:8080',
        key: settings.auto_login?.environments?.key || '', // 从environments中读取key
      });
      message.success('设置加载成功');
    } catch (error) {
      console.error('加载设置失败:', error);
      message.error('加载设置失败');
    }
  }

  // 保存自动登录设置
  async function saveSettings() {
    try {
      loading.value = true;
      // 先获取当前完整设置
      const currentSettings = await invoke<any>('get_user_settings');

      const success = await invoke<boolean>('save_user_settings', {
        settings: {
          nickname: currentSettings.nickname || '',
          theme: currentSettings.theme || 'light',
          database: currentSettings.database || {
            host: 'localhost',
            port: 1521,
            service_name: 'ORCL',
            username: 'AH_SLM4',
            password: '2',
          },
          auto_login: {
            environments: {
              env_55: formValue.env55,
              env_54: formValue.env54,
              localhost: formValue.localhost,
              key: formValue.key, // 新增key字段保存
            },
            database: currentSettings.auto_login?.database || {
              host: 'localhost',
              port: 1521,
              service_name: 'ORCL',
              username: 'AH_SLM4',
              password: '2',
            },
          },
          ai_settings: currentSettings.ai_settings || {},
        },
      });

      if (success) {
        message.success('设置保存成功');
      } else {
        message.error('设置保存失败');
      }
    } catch (error) {
      console.error('保存设置失败:', error);
      message.error(`保存设置失败: ${error}`);
    } finally {
      loading.value = false;
    }
  }

  // 表单提交
  function formSubmit() {
    formRef.value.validate((errors: any) => {
      if (!errors) {
        saveSettings();
      } else {
        message.error('请填写完整信息');
      }
    });
  }

  // 组件挂载时加载设置
  onMounted(() => {
    loadSettings();
  });
</script>

<style lang="less" scoped>
  .n-form {
    max-width: 600px;
  }

  .mb-4 {
    margin-bottom: 16px;
  }
</style>
